package cn.fl.flowauth.service.impl;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysOrgApiService;
import cmm.user.facade.system.dto.SysOrgDTO;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.flowauth.api.IPrjFlowAuthCtrlApiService;
import cn.fl.flowauth.condition.PrjFlowAuthCtrlQC;
import cn.fl.flowauth.dto.PrjFlowAuthCtrlDTO;
import cn.fl.flowauth.service.IPrjFlowAuthCtrlService;
import cn.fl.flowauth.transform.PrjFlowAuthCtrlVOTransform;
import cn.fl.flowauth.vo.PrjFlowAuthCtrlVO;
import cn.fl.framework.base.constant.WebBaseConstant;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Description: 项目流程权限控制 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class PrjFlowAuthCtrlServiceImpl implements IPrjFlowAuthCtrlService {

	/**
	 * 日志
	 */
	private static final Logger logger = LoggerFactory.getLogger(IPrjFlowAuthCtrlService.class);
	
	/**
	 * TODO 自定义 API 暴露服务
	 */
	//@Autowired
	//private I自定义ApiService 自定义ApiService;

	@Autowired
	private ISysOrgApiService sysOrgApiService;

	@Autowired
	private IPrjFlowAuthCtrlApiService prjFlowAuthCtrlApiService;

	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;

	@Override
	public PrjFlowAuthCtrlVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "selectById", "主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		PrjFlowAuthCtrlVO vo = PrjFlowAuthCtrlVOTransform.toVO(this.prjFlowAuthCtrlApiService.selectById(id));
		BaseLogUtils.newLogger("selectById.End.id:{},vo:{}", id, JSON.toJSONString(vo)).info();
		if (null != vo && StringUtils.isNotEmpty(vo.getPassiveCtrlOrgCd())) {
			//事业部组织架构
			List<SysOrgDTO> list = this.sysOrgApiService.searchSysOrgListBy(CurrentThreadContext.getCurrentSysCd());
			Map<String, SysOrgDTO> buOrgCdMap = new HashMap<>();
			if (CollectionUtils.isNotEmpty(list)) {
				for (SysOrgDTO sysOrgDTO : list) {
					buOrgCdMap.put(sysOrgDTO.getOrgCd(), sysOrgDTO);
				}
			}
			if (buOrgCdMap.containsKey(vo.getPassiveCtrlOrgCd())){
				SysOrgDTO sysOrgDTO = buOrgCdMap.get(vo.getPassiveCtrlOrgCd());
				vo.setBuOrgCdNm(sysOrgDTO.getOrgDispNm());
			}
		}
		BaseLogUtils.newLogger("selectById.End2.id:{}", id).info();
		return vo;
	}

	@Override
	public Long add(PrjFlowAuthCtrlVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "add", "新增对象不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		//return this.prjFlowAuthCtrlApiService.add(PrjFlowAuthCtrlVOTransform.toDTO(entity));
		//TODO 业务逻辑
		return null;
	}

	@Override
	public boolean removeById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "removeById", "删除主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		}
		//return this.prjFlowAuthCtrlApiService.removeById(id);
		//TODO 业务逻辑
		return false;
	}
	
	/**
     * 删除
     * @param ids
     * @return
     */
    public boolean removeByIds(List<Long> ids)throws BaseException{
    	if(CollectionUtils.isEmpty(ids)){
    		BaseLogUtils.info(logger, "removeByIds", "删除主键参数集合不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		};
		return false;
    }

	@Override
	public boolean modify(PrjFlowAuthCtrlVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "modify", "修改对象参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		}
		return this.prjFlowAuthCtrlApiService.modify(PrjFlowAuthCtrlVOTransform.toDTO(entity));
	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException{
		if(null == page)page = new Pager();
		Pager pager = prjFlowAuthCtrlApiService.searchListPage(page);
		if (CollectionUtils.isNotEmpty(pager.getResultList())) {
			List<PrjFlowAuthCtrlVO> voList = PrjFlowAuthCtrlVOTransform.toVOList((List<PrjFlowAuthCtrlDTO>) pager.getResultList());
			for (PrjFlowAuthCtrlVO prjFlowAuthCtrlVO : voList) {
				if (prjFlowAuthCtrlVO.getIsValid() == 1) {
					prjFlowAuthCtrlVO.setIsShowModifyBtn(1);
				} else {
					prjFlowAuthCtrlVO.setIsShowModifyBtn(0);
				}
				if (prjFlowAuthCtrlVO.getCtrlStartDt() != null && DateUtils.after(prjFlowAuthCtrlVO.getCtrlStartDt(),new Date())
						&& prjFlowAuthCtrlVO.getCtrlEndDt() != null && DateUtils.before(prjFlowAuthCtrlVO.getCtrlEndDt(),new Date())
						&& prjFlowAuthCtrlVO.getIsValid() == 1) {
					prjFlowAuthCtrlVO.setIsValid(1);
				} else {
					prjFlowAuthCtrlVO.setIsValid(0);
				}
			}
			this.setDictData(voList);
			pager.setResultList(voList);
		}
		return pager;
	}

	@Override
	public List<PrjFlowAuthCtrlVO> searchList(PrjFlowAuthCtrlQC qc) throws BaseException {
		if (null == qc) {
			BaseLogUtils.newLogger("查询参数为空,操作人：{}", CurrentThreadContext.getCurrentUserName()).info();
			return null;
		}
		return PrjFlowAuthCtrlVOTransform.toVOList(prjFlowAuthCtrlApiService.searchList(qc));
	}

	@Override
	public List<KeyValueVO> searchBusinessOrgList() throws BaseException {
		List<SysOrgDTO> list = this.sysOrgApiService.searchListByOrgTypCd(WebBaseConstant.SYS_SYS_CD);
		List<KeyValueVO> kvList = new ArrayList();
		if (CollectionUtils.isNotEmpty(list)) {
			for (SysOrgDTO sysOrgDTO : list) {
				KeyValueVO kv = new KeyValueVO();
				kv.setKey(sysOrgDTO.getOrgCd());
				kv.setValue(sysOrgDTO.getOrgNm());
				kvList.add(kv);
			}
		}
		return kvList;
	}

	@Override
	public List<KeyValueVO> getCtrlContent() throws BaseException {
		return this.getKeyValueList(DictionaryConstant.PRJ_FLOW_AUTH_CTRL_CONTENT);
	}

	@Override
	public List<KeyValueVO> getCtrlReason() throws BaseException {
		return this.getKeyValueList(DictionaryConstant.PRJ_FLOW_AUTH_CTRL_REASON);
	}

	@Override
	public List<KeyValueVO> searchYNList() throws BaseException {
		return this.getKeyValueList(DictionaryConstant.CODE_SYS_YES_NO_CD);
	}

	@Override
	public boolean batchAdd(List<PrjFlowAuthCtrlVO> voList) throws BaseException {
		if (CollectionUtils.isEmpty(voList)) {
			BaseLogUtils.info(logger, "batchAdd", "新增对象参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		}
		return this.prjFlowAuthCtrlApiService.batchAdd(PrjFlowAuthCtrlVOTransform.toDTOList(voList));
	}

	@Override
	public boolean modifyIsvalid(Long id, Integer isValid) {
		if (StringUtils.isEmpty(id)) {
			BaseLogUtils.info(logger, "modifyIsvalid", "修改prjFlowAuthCtrl状态ID为空.DATA:" + id, CurrentThreadContext.getCurrentUserName());
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
		}
		return this.prjFlowAuthCtrlApiService.modifyIsValid(id, isValid);
	}

	private List<KeyValueVO> getKeyValueList(String code) throws BaseException {
		List<KeyValueVO> keyValueList = null;
		List<SysDictionaryDTO> dictionaryList = this.sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), code);
		if (CollectionUtils.isNotEmpty(dictionaryList)) {
			keyValueList = new ArrayList<>();
			for (SysDictionaryDTO sysDictionaryDTO : dictionaryList) {
				KeyValueVO keyValue = new KeyValueVO();
				keyValue.setKey(sysDictionaryDTO.getCode());
				keyValue.setValue(sysDictionaryDTO.getCodeNm());
				keyValueList.add(keyValue);
			}
		}
		return keyValueList;
	}

	/**
	 * 添加数据字典名称
	 *
	 * @param voList
	 */
	private void setDictData(List<PrjFlowAuthCtrlVO> voList) {
		if (CollectionUtils.isEmpty(voList)) return;

		List<SysDictionaryDTO> dictionaryList = this.sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(),
				CurrentThreadContext.getCurrentOrgCd(), DictionaryConstant.CODE_SYS_YES_NO_CD);
		Map<Integer, SysDictionaryDTO> isValidMap = new HashMap<>();
		if (CollectionUtils.isNotEmpty(dictionaryList)) {
			for (SysDictionaryDTO dto : dictionaryList) {
				isValidMap.put(Integer.valueOf(dto.getCode()), dto);
			}
		}
		//事业部组织架构
		List<SysOrgDTO> list = this.sysOrgApiService.searchSysOrgListBy(CurrentThreadContext.getCurrentSysCd());
		Map<String, SysOrgDTO> buOrgCdMap = new HashMap<>();
		if (CollectionUtils.isNotEmpty(list)) {
			for (SysOrgDTO sysOrgDTO : list) {
				buOrgCdMap.put(sysOrgDTO.getOrgCd(), sysOrgDTO);
			}
		}
		SysOrgDTO sysOrgDTO = null;
		String orgCd = null;

		Map<String, String> prjTypCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(),
				CurrentThreadContext.getCurrentOrgCd(), DictionaryConstant.CODE_PRJ_TYPE_CD);
		if (CollectionUtils.isMapEmpty(prjTypCdMap)) {
			prjTypCdMap = new HashMap<>(1);
		}
		prjTypCdMap.put("ALL", "全部");

		Map<String, String> ctrlContentMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(),
				CurrentThreadContext.getCurrentOrgCd(), DictionaryConstant.PRJ_FLOW_AUTH_CTRL_CONTENT);
		if (CollectionUtils.isMapEmpty(ctrlContentMap)) {
			ctrlContentMap = new HashMap<>(1);
		}
		ctrlContentMap.put("ALL", "全部");

		for (PrjFlowAuthCtrlVO vo : voList) {
			if (isValidMap.containsKey(vo.getIsValid())) {
				SysDictionaryDTO dto = isValidMap.get(vo.getIsValid());
				vo.setIsValidNm(dto.getCodeNm());
			}
			//获取所属事业部
			if (vo.getPassiveCtrlOrgCd().length() >= 8) {
				String buOrgCd = vo.getPassiveCtrlOrgCd().substring(0, 8);
				if (buOrgCdMap.containsKey(buOrgCd)){
					sysOrgDTO = buOrgCdMap.get(buOrgCd);
					vo.setBuOrgCdNm(sysOrgDTO.getOrgNm());
				}
			}else {
				sysOrgDTO = buOrgCdMap.get("0000");
				vo.setBuOrgCdNm(sysOrgDTO.getOrgNm());
			}
			//获取省公司和分公司
			if (buOrgCdMap.containsKey(vo.getPassiveCtrlOrgCd())) {
				sysOrgDTO = buOrgCdMap.get(vo.getPassiveCtrlOrgCd());
				orgCd = sysOrgDTO.getOrgCd();
				while(orgCd.length()>8){
					if("4".equals(sysOrgDTO.getOrgTypCd())){//分公司
						vo.setCyOrgCdNm(sysOrgDTO.getOrgNm());
					}else if("3".equals(sysOrgDTO.getOrgTypCd())){
						vo.setPrOrgCdNm(sysOrgDTO.getOrgNm());
						break;
					}
					orgCd = orgCd.substring(0,orgCd.length()-4);
					if(buOrgCdMap.containsKey(orgCd)){
						sysOrgDTO = buOrgCdMap.get(orgCd);
					}else{
						break;
					}
				}
			}
			if (prjTypCdMap != null) {
				if (StringUtils.isNotBlank(vo.getCtrlPrjTypCd())) {
					String[] prjTypCdArray = vo.getCtrlPrjTypCd().split(";");
					StringBuffer prjTypCdNm = new StringBuffer("");
					for (String prjTypCd : prjTypCdArray) {
						if (prjTypCdMap.containsKey(prjTypCd)) {
							prjTypCdNm.append(prjTypCdMap.get(prjTypCd));
						} else {
							prjTypCdNm.append(prjTypCd);
						}
						prjTypCdNm.append("、");
					}
					vo.setCtrlPrjTypCdNm(prjTypCdNm.toString().substring(0, prjTypCdNm.toString().length() - 1));
				}
			}
			if (ctrlContentMap != null) {
				if (StringUtils.isNotBlank(vo.getCtrlContent())) {
					String[] ctrlContentArray = vo.getCtrlContent().split(";");
					StringBuffer ctrlContentNm = new StringBuffer("");
					for (String ctrlContent : ctrlContentArray) {
						if (ctrlContentMap.containsKey(ctrlContent)) {
							ctrlContentNm.append(ctrlContentMap.get(ctrlContent));
						} else {
							ctrlContentNm.append(ctrlContent);
						}
						ctrlContentNm.append("、");
					}
					vo.setCtrlContentNm(ctrlContentNm.toString().substring(0, ctrlContentNm.toString().length() - 1));
				}
			}
		}
	}
}
